package com.study.book.gym.char03;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/**
 * @author study
 * @version 1.0
 * @date 2021/5/13 11:24
 */
public class CyclicBarrierDemo {
    public static void main(String[] args) {
        final int N = 2;
        Thread[] allSoldier = new Thread[N];
        boolean flag = false;
        final BarrierRun barrierRun = new BarrierRun(flag, N);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(N, barrierRun);
        //设置屏障点，主要是为了执行方法
        System.out.println("集合队伍！");
        for (int i = 0; i < N; i++) {
            System.out.println("士兵 " + i + " 报道！");
            allSoldier[i] = new Thread(new Soldier(cyclicBarrier, "士兵" + i));
            allSoldier[i].start();
        }
    }

    public static class Soldier implements Runnable {
        private final CyclicBarrier cyclic;
        private String soldier;

        public Soldier(CyclicBarrier cyclic, String soldier) {
            this.soldier = soldier;
            this.cyclic = cyclic;
        }

        @Override
        public void run() {
            try {
                //等待所有士兵到到齐
                cyclic.await();
                doWork();
                //等待所有士兵完成工作
                cyclic.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        private void doWork() {
            try {
                TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(5));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(soldier + " 任务完成 ");
        }
    }

    public static class BarrierRun implements Runnable {
        boolean flag;
        int N;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            N = n;
        }

        @Override
        public void run() {
            if (flag) {
                System.out.println("司令 " + N + "个，任务完成！");
            } else {
                System.out.println("司令 " + N + "个，集合完成！");
                flag = true;
            }
        }
    }
}
